<template>
  <el-container>
  <div class="video-box">
    <video :src="src"
                           :muted="false"
                           :autoplay="isPlay"

                           ref="video"
                           :title="title"
                           controls="controls"
                           @touchmove.prevent
                           @pause="pause"
                           @play="play"
                           @ended="pause"
                           @loadeddata="setVideoPoster($event)"
           style="height: 340px"
    ></video></div>
  <div v-if="disabled" class="cover-outer" >
    <div v- v-if="!isPlay">
    <i class="el-icon-video-play" style="font-size: 100px; color:rgba(255,255,255,0.7);" @click="play"></i>
    </div>

  </div>
  </el-container>
</template>

<script>
export default {
  name: "video",
  props: {
    src:String,

  },
  data(){
    return{
      isPlay: false,
      disabled: true

    }
  },
  mounted() {
    this.$bus.$on('stopVideo',this.pause) // 子组件接受数据
  },
  beforeDestroy() {
    this.$bus.$off('stopVideo') // 销毁前清除事件监听
  },
  methods: {
    clearTimer() {
      this.timer && clearTimeout(this.timer)
    },
    play() {
      this.$bus.$emit('stopVideo') // 子组件发送数据
      this.clearTimer()
      this.isPlay = true
      // 防止点击穿透
      this.timer = setTimeout(() => {
        this.disabled = false
      }, 500)
      if (this.$refs.video) {
        this.$nextTick(() => {
          this.$refs.video.play()
        })
      }
    },
    pause() {
      this.clearTimer()
      this.isPlay = false
      this.disabled = true
    },
    setVideoPoster(event) {
          let video = event.target;
          // video.height = video.clientHeight;
          let canvas = document.createElement("canvas"); // 创建 canvas
          const ctx = canvas.getContext("2d");
          video.currentTime = 1; // 第一帧
          video.oncanplay = () => {
            canvas.width = video.clientWidth; // 获取视频宽度
            canvas.height = video.clientHeight; //获取视频高度
            var img = new Image(); // 这里使用img是为了解决视频跨域 canvas.toDataURL会提示错误的问题
            img.onload = function () {
              // canvas绘图
              ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
              // 转换成base64形式并设置封面
              video.poster = canvas.toDataURL("image/jpeg", 1); // 截取后的视频封面
            }
      }
    }
  }
}
</script>

<style scoped>
.videoname{
  position: relative;
  width: 80%;
  left: 10%;
  top: 30px;
  height: 50px;
  background-color: white;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
}
.video-box{
  height: 310px;
}
.cover-outer{
  position: absolute;
  top:30%;
  left: 40%;
  width: 100px;
  height: 100px;
}
</style>
